import app_config from './app_config.js'
let app = false;

function request(p) {
	p.url = app_config.domain + p.url
	p.header = {
		'Content-Type': 'application/x-www-form-urlencoded'
	};

	let success_cb = p.success
	let user_token = uni.getStorageSync('user_token');
	user_token && (p.header.token = user_token);
	p.success = (res) => {
		uni.hideLoading()
		let result = res.data
		if (result.code == 2333) {
			uni.clearStorage()
			h5_get_code()
		} else {
			if (success_cb) success_cb(res);
		}
	}
	
	uni.showLoading({
		title: 'loading...'
	});
	uni.request(p);
}

function h5_get_code() {
	//获取code
	var redirect_uri = encodeURIComponent(location.origin + location.pathname + location.hash)
	var url = `${app_config.code_url}?redirect_uri=${redirect_uri}`
	location.href = url
}

function appLogin(fn){
	let token_expire_time = uni.getStorageSync('token_expire_time')
	let user_token = uni.getStorageSync('user_token')
	let user_info = uni.getStorageSync('user_info')

	if(((user_token.length)>0)&&((Date.parse(new Date())/1000)<token_expire_time)){
		fn&&fn(user_info)
		return true;
	}
	let activity_id = getQueryString("activity_id")
	let code = getQueryString("code")
	
	if (!code) {
		h5_get_code()
		return false
	}
	
	uni.request({
		
		url: app_config.domain + "api/wx_h5_login",
		header: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		data: {
			code: code,
			activity_id:activity_id
		},
		method: 'POST',
		success: (res) => {
			var res = res.data
			if (res.code == 2333) {
				uni.clearStorage()
				h5_get_code()
			} else {
				uni.setStorageSync('user_token', res['result']['token']);
				uni.setStorageSync('user_info', res['result']['user_info']);
				uni.setStorageSync('token_expire_time', (Date.parse(new Date())/1000) + parseInt(res['result']['expire_time']));
				let set_url = location.origin + location.pathname+'?from=web'+ location.hash
				window.history.pushState({},0,set_url)
				fn && fn(user_info)
			}
		},
	})
}

function getQueryString(name) {
	return decodeURIComponent((new RegExp('[?|&]' +
	      name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}

Date.prototype.format = function(format) {
	var date = {
		"M+": this.getMonth() + 1,
		"d+": this.getDate(),
		"h+": this.getHours(),
		"m+": this.getMinutes(),
		"s+": this.getSeconds(),
		"q+": Math.floor((this.getMonth() + 3) / 3),
		"S+": this.getMilliseconds()
	};
	if (/(y+)/i.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
	}
	for (var k in date) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ?
				date[k] : ("00" + date[k]).substr(("" + date[k]).length));
		}
	}
	return format;
}

function rand(min, max) {
	return Math.floor(Math.random() * (max - min)) + min;
}

//oss上传图片
function ossUpFile(file, fn) {
	request({
		url: app_config.oss_upurl,
		passLoading: 1,
		success: (res) => {
			var res = res.data
			var ext = file.name ? file.name.split('.')[1] : "jpg";
			var key = (res.dir || "") + (new Date()).format('yyyyMMddhhmmss') + rand(1000, 9999) + "." + ext;

			uni.uploadFile({
				url: res.result.host, //仅为示例，非真实的接口地址
				// url: app_config.domain2,
				filePath: file.path,
				name: 'file',
				formData: {
					'OSSAccessKeyId': res.result.accessid,
					'policy': res.result.policy,
					'signature': res.result.signature,
					'expire': res.result.expire,
					'success_action_status': '200',
					'key': 'web/' + key,
				},
				success: () => {
					fn && fn(res.result.host + "/" + "web/" + key, 'web/' + key)
					//return res.result.host+ "/" + "web/"+key, 'web/'+key;
				}
			});
		}
	})
}

//设置分享
function setShare(share = {}) {
	!app && (app = getApp())
	app.$wx.ready(function() {
		//需在用户可能点击分享按钮前就先调用
		app.$wx.updateTimelineShareData({
			title: share.title || app_config.title, // 分享标题
			link: share.link || location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
			imgUrl: share.imgUrl || '', // 分享图标
			success: function() {
				// 设置成功
				console.log('设置成功')
			}
		})
		app.$wx.updateAppMessageShareData({
			title: share.title || app.globalData.sys_config.title || app_config.title, // 分享标题
			desc: share.desc || '', // 分享描述
			link: share.link || location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
			imgUrl: share.imgUrl || app.globalData.sys_config.logo || '', // 分享图标
			success: function() {
				// 设置成功
				console.log('设置成功')
			}
		})
	});
}


module.exports = {
	request: request,
	app_config: app_config,
	getQueryString: getQueryString,
	appLogin: appLogin,
	ossUpFile: ossUpFile,
	setShare: setShare
}
